package com.wsch.client;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.wsch.client.domain.WDocVirtualField;
import com.alibaba.fastjson.JSON;
import com.wsch.client.domain.WDocAppDic;
import com.wsch.client.domain.WDocAppDicUnit;
import com.wsch.client.domain.WDocAppModel;
import com.wsch.client.domain.WDocField;
import com.wsch.client.domain.WProjectInfo;
import com.wsch.client.domain.WschUser;
import com.wsch.client.https.HttpUtils;
import com.wsch.client.utils.WtcJsonMap;

public class WschClient {
	private String secret;
	private String operatorLoginname;
	private String operatorPassword;
	private String baseUrl;

	/**
	 * @param baseUrl
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 */
	public WschClient(String baseUrl, String secret, String operatorLoginname, String operatorPassword) {
		super();
		this.secret = secret;
		this.baseUrl = baseUrl;
		this.operatorLoginname = operatorLoginname;
		this.operatorPassword = operatorPassword;
	}

	/**
	 * 校驗接口執行情況
	 * 
	 * @param url
	 * 
	 * @param json
	 */
	private void validateBackJson(String url, JSONObject json) {
		String state = json.get("STATE").toString();
		if (state.equals("1")) {
			throw new RuntimeException(json.get("MESSAGE").toString() + " by " + url);
		}
	}

	/**
	 * 获得远程参数（默认注册了权限相关参数）
	 * 
	 * @return
	 */
	private Map<String, String> initParas() {
		Map<String, String> data = new HashMap<String, String>();
		data.put("secret", secret);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		return data;
	}

	/**
	 * 接口是否可用
	 * 
	 * @param isThrowException
	 * @return
	 */
	public boolean isLive(boolean isThrowException) {
		Map<String, String> data = initParas();
		data.put("loginname", operatorLoginname);
		JSONObject backData = HttpUtils.httpPost(baseUrl + "/api/get/user.do", data);
		if (!backData.has("STATE") || backData.getInt("STATE") != 0) {
			if (isThrowException) {
				throw new RuntimeException(backData.toString());
			} else {
				return false;
			}
		}
		return true;
	}

	public WProjectInfo getProject(String key) {
		Map<String, String> data = initParas();
		data.put("key", key);
		String url = baseUrl + "/api/index/project/get.do";
		JSONObject json = HttpUtils.httpPost(url, data);

		validateBackJson(url, json);
		WtcJsonMap wjm = new WtcJsonMap(json.toMap());
		// -------------------------------------
		if (!wjm.has("DATA")) {
			return null;
		}
		WProjectInfo info = new WProjectInfo();
		info.setId(wjm.getString("DATA", "id"));
		info.setKey(wjm.getString("DATA", "keyid"));
		info.setName(wjm.getString("DATA", "name"));
		info.setSort(wjm.getInt("DATA", "sort"));
		info.setState(wjm.getString("DATA", "pstate"));
		return info;
	}

	/**
	 * 注册项目检索字段
	 * 
	 * @param field
	 */
	public void registField(String projectKey, WDocField field) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.putAll(field.getMap());
		String url = baseUrl + "/api/index/regist/field.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 注册项目业务模型
	 * 
	 * @param projectKey
	 * @param model
	 */
	public void registAppModel(String projectKey, WDocAppModel model) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.putAll(model.getMap());
		String url = baseUrl + "/api/index/regist/appmodel.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 注册项目业务虚拟字段
	 * 
	 * @param projectKey
	 * @param key
	 * @param field
	 */
	public void registVirtualField(String projectKey, String key, WDocVirtualField field) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.put("appKey", key);
		data.putAll(field.getMap());
		String url = baseUrl + "/api/index/regist/virtualfield.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);

	}

	/**
	 * 注册一个检索字典(一级)
	 * 
	 * @param projectKey
	 * @param appDic_Catalog
	 * @return 字典类型ID
	 */
	public String registAppDic(String projectKey, WDocAppDic appdic) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.putAll(appdic.getMap());
		String url = baseUrl + "/api/index/regist/appdic.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
		WtcJsonMap wjm = new WtcJsonMap(json.toMap());
		// -------------------------------------
		if (!wjm.has("DATA")) {
			return null;
		} else {
			return wjm.getString("DATA");
		}
	}

	/**
	 * 清理检索字典的所有子项
	 * 
	 * @param projectKey
	 * @param appdicId
	 */
	public void clearAppDicNodes(String projectKey, String appdicId) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.put("appdicid", appdicId);
		String url = baseUrl + "/api/index/clear/appdic.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 添加一个检索字典的子项
	 * 
	 * @param projectKey
	 * @param appdicId
	 * @param wDocAppDicUnit
	 * @return 字典子项ID
	 */
	public String addAppDicNode(String projectKey, String appdicId, WDocAppDicUnit wDocAppDicUnit) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.putAll(wDocAppDicUnit.getMap());
		String url = baseUrl + "/api/index/add/appdicnode.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
		WtcJsonMap wjm = new WtcJsonMap(json.toMap());
		// -------------------------------------
		if (!wjm.has("DATA")) {
			return null;
		} else {
			return wjm.getString("DATA");
		}
	}

	/**
	 * 删除检索权限组
	 * 
	 * @param projectKey
	 * @param groupname  权限组key，为空时删除全部权限组(关键字右侧模糊匹配)
	 */
	public void delPopGroups(String projectKey, String groupname) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.put("groupname", groupname);
		String url = baseUrl + "/api/index/del/popgroups.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 初始化一个权限组(获取或创建)
	 * 
	 * @param projectKey
	 * @param groupname 权限组名称（通过该参数判断是否已有权限组）
	 * @param note
	 * @return
	 */
	public String initPopGroup(String projectKey, String groupname, String note) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.put("groupname", groupname);
		data.put("note", note);
		String url = baseUrl + "/api/index/init/popgroup.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
		WtcJsonMap wjm = new WtcJsonMap(json.toMap());
		// -------------------------------------
		if (!wjm.has("DATA")) {
			return null;
		} else {
			return wjm.getString("DATA");
		}
	}

	/**
	 * 添加一个权限组用户
	 * 
	 * @param gourpid
	 * @param key     （不重复）
	 */
	public void addUser(String gourpid, String key) {
		Map<String, String> data = initParas();
		data.put("gourpid", gourpid);
		data.put("key", key);
		String url = baseUrl + "/api/index/add/popuser.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 添加一个权限组权限
	 * 
	 * @param gourpid
	 * @param key     （不重复）
	 */
	public void addPopKey(String groupid, String keys) {
		Map<String, String> data = initParas();
		data.put("groupid", groupid);
		data.put("keys", keys);
		String url = baseUrl + "/api/index/add/popkey.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 查找一个用户
	 * 
	 * @param loginname
	 * @return
	 */
	public WschUser getUser(String loginname) {
		Map<String, String> data = initParas();
		data.put("loginname", loginname);
		String url = baseUrl + "/api/get/user.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
		WtcJsonMap wjm = new WtcJsonMap(json.toMap());
		// -------------------------------------
		if (!wjm.has("DATA")) {
			return null;
		} else {
			List<WtcJsonMap> list = wjm.getList("DATA", "list");
			if (list.size() <= 0) {
				return null;
			} else {
				WschUser user = new WschUser();
				user.setLoginname(list.get(0).getString("LOGINNAME"));
				user.setName(list.get(0).getString("NAME"));
				user.setRemoteId(list.get(0).getString("ID"));
				return user;
			}
		}
	}

	/**
	 * 创建用户
	 * 
	 * @param wschuser
	 */
	public void addUser(WschUser wschuser) {
		Map<String, String> data = initParas();
		data.put("name", wschuser.getName());
		data.put("loginname", wschuser.getLoginname());
		String url = baseUrl + "/api/post/user.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 修改用户
	 * 
	 * @param wschuser
	 */
	public void editUser(WschUser wschuser) {
		Map<String, String> data = initParas();
		data.put("id", wschuser.getRemoteId());
		data.put("name", wschuser.getName());
		data.put("loginname", wschuser.getLoginname());
		String url = baseUrl + "/api/put/user.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 添加权限组权限（批量）
	 * 
	 * @param gourpid
	 * @param popids
	 */
	public void addPopKey(String gourpid, List<String> popids) {
		StringBuffer ids = new StringBuffer();
		for (String popid : popids) {
			if (ids.length() > 0) {
				ids.append(",");
			}
			ids.append(popid);
			if (ids.length() > 1048) {
				addPopKey(gourpid, ids.toString());
				ids = new StringBuffer();
			}
		}
		if (ids.length() > 0) {
			addPopKey(gourpid, ids.toString());
		}
	}

	/**
	 * 添加索引
	 * 
	 * @param projectId
	 * @param taskkey
	 * @param hashMap
	 */
	public void addIndex(String projectId, String taskkey, Map<String, String> hashMap) {
		Map<String, String> data = initParas();
		data.put("projectid", projectId);
		data.put("taskkey", taskkey);
		data.put("jsonstr", JSON.toJSONString(hashMap));
		String url = baseUrl + "/api/index/add.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);

	}

	/**
	 * 执行索引
	 * 
	 * @param projectId
	 * @param taskkey
	 */
	public void runIndex(String projectId, String taskkey) {
		Map<String, String> data = initParas();
		data.put("projectid", projectId);
		data.put("taskkey", taskkey);
		String url = baseUrl + "/api/index/run.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);

	}

	/**
	 * 删除全部索引
	 * 
	 * @param projectKey
	 * @param appkeyid   可空，为空时删除全部索引
	 */
	public void removeAllIndex(String projectKey, String appkeyid) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		if (StringUtils.isNotBlank(appkeyid)) {
			data.put("appkeyid", appkeyid);
		}
		String url = baseUrl + "/api/index/removeall.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}

	/**
	 * 删除一条索引
	 * 
	 * @param parameter
	 * @param appid
	 */
	public void removeIndex(String projectKey, String appid) {
		Map<String, String> data = initParas();
		data.put("projectKey", projectKey);
		data.put("appid", appid);
		String url = baseUrl + "/api/index/del.do";
		JSONObject json = HttpUtils.httpPost(url, data);
		validateBackJson(url, json);
	}
}
